<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 12/9/18
 * Time: 8:48 PM
 */

require_once __DIR__.'/vendor/autoload.php';
use Workerman\Worker;

$ws = new Worker('Websocket://0.0.0.0:7777');

$ws->onConnect = function ($con) {
    $con->onWebSocketConnect = function ($con, $http_header) {
        echo "New connection\n";
        // 可以在这里判断连接来源是否合法，不合法就关掉连接
        // $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
        //if($_SERVER['HTTP_ORIGIN'] != 'http://chat.workerman.net')
        //{
            //$con->close();
        //}
        // onWebSocketConnect 里面$_GET $_SERVER是可用的
        // var_dump($_GET, $_SERVER);
    };
};

$ws->onMessage = function ($con, $data) use ($ws) {
    echo "received: $data\n";
    foreach ($ws->connections as $client) {
        $client->send('broadcast');
    }
};

$ws->onClose = function ($con) {
    echo "Connection closed\n";
    $con->close();
};

Worker::runAll();